/* NOTICE
    OpenJaWS - Open Java Weather Station
    
    Copyright (C) 2008 Grant Gardner <grant@lastweekend.com.au>
    
    OpenJaWS is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
    
NOTICE */

package au.com.lastweekend.openjaws.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;

/**
 * Runnable that eats lines from an InputStream or Reader
 * 
 * Internally uses a BufferedReader to get lines from the input stream.
 * 
 * @author ggardner
 * 
 */
public abstract class LineGobbler implements Runnable {

    private BufferedReader reader;

    public LineGobbler(InputStream is) {

        this(new InputStreamReader(is));
    }

    public LineGobbler(Reader reader) {

        this(new BufferedReader(reader));
    }

    public LineGobbler(BufferedReader reader) {

        this.reader = reader;
    }

    public final void run() {

        String line;
        try {
            while ((line = reader.readLine()) != null) {
                gobble(line);
            }
        } catch (IOException e) {
            handleReaderException(e);
        }

    }

    /**
     * Do something with the line of input
     * 
     * @param line
     */
    protected abstract void gobble(String line);

    /**
     * BufferedReader throws IOException. Override this method if you want to do something other than wrap it in a run-time
     * exception.
     * 
     * @param e
     */
    protected void handleReaderException(IOException e) {

        throw new RuntimeException("IOException while gobbling from " + reader, e);
    }

}